/*	$Id: buf.c 1103 2010-12-02 03:09:21Z phrakt $	*/
/*	$OpenBSD: buf.c,v 1.60 2007/02/22 06:42:09 otto Exp $	*/
/*
 * Copyright (c) 2003 Jean-Francois Brousseau <jfb@openbsd.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/time.h>

#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "buf.h"
#include "log.h"
#include "mem.h"
#include "string.h"
#include "private.h"


#define BUF_INCR	128

struct cnp_buf {
	unsigned int    cb_flags;

	/* buffer handle, buffer size, and data length */
	uint8_t	       *cb_buf;
	size_t	        cb_size;
	size_t	        cb_len;
	size_t          cb_pos;		/* current position */
};

#define SIZE_LEFT(b)	(b->cb_size - b->cb_len)



/*
 * cnp_buf_alloc()
 *
 * Create a new buffer structure and return a pointer to it.  This structure
 * uses dynamically-allocated memory and must be freed with cnp_buf_free(),
 * once the buffer is no longer needed.
 *
 * Returns a pointer to the newly allocated buffer on success, or NULL on
 * failure.
 */
cnp_buf_t*
cnp_buf_alloc(size_t len, unsigned int flags)
{
	cnp_buf_t *buf;

	if ((buf = cnp_malloc(sizeof(*buf))) == NULL) {
		cnp_log_err(cnp_logchan, "failed to allocate buffer");
		return (NULL);
	}

	/* Postpone creation of zero-sized buffers */
	if (len > 0) {
		if ((buf->cb_buf = cnp_calloc(1, len)) == NULL) {
			cnp_free(buf);
			return (NULL);
		}
	}
	else
		buf->cb_buf = NULL;

	buf->cb_flags = flags;
	buf->cb_size = len;
	buf->cb_len = 0;
	buf->cb_pos = 0;

	return (buf);
}

/*
 * cnp_buf_load()
 *
 * Load the contents of the file located at <path>, starting at offset <offset>,
 * into a buffer allocated with the flags <flags>.  The file descriptor is
 * closed once there is no more data to read.
 *
 * Returns a pointer to the buffer with the loaded contents on success, or
 * NULL on failure.
 */
cnp_buf_t*
cnp_buf_load(const char *path, off_t offset, unsigned int flags)
{
	int fd;
	cnp_buf_t *bp;

	if ((fd = open(path, O_RDONLY, 0600)) == -1) {
		cnp_log_errno(cnp_logchan,
		    "cnp_buf_load: failed to load '%s'", path);
		return (NULL);
	}

	bp = cnp_buf_loadfd(fd, offset, flags);

	(void)close(fd);
	return (bp);
}

/*
 * cnp_buf_loadfd()
 *
 * Load data from the file descriptor <fd>, starting at offset <offset>,
 * into a buffer allocated with the flags <flags>.
 *
 * Returns a pointer to the buffer with the loaded contents on success, or
 * NULL on failure.
 */
cnp_buf_t*
cnp_buf_loadfd(int fd, off_t offset, unsigned int flags)
{
	ssize_t ret;
	size_t len;
	uint8_t *bp;
	struct stat st;
	cnp_buf_t *buf;

	if (fstat(fd, &st) == -1) {
		cnp_log_errno(cnp_logchan, "cnp_buf_loadfd: fstat");
		return (NULL);
	}

	if (lseek(fd, offset, SEEK_SET) == -1) {
		cnp_log_errno(cnp_logchan, "cnp_buf_loadfd: lseek");
		return (NULL);
	}

	if ((buf = cnp_buf_alloc(st.st_size, flags)) == NULL)
		return (NULL);

	for (bp = buf->cb_buf; ; bp += (size_t)ret) {
		len = SIZE_LEFT(buf);
		ret = read(fd, bp, len);
		if (ret == -1)
			cnp_log_errno(cnp_logchan,
			    "cnp_buf_load: read error");
		else if (ret == 0)
			break;

		buf->cb_len += (size_t)ret;
	}

	return (buf);
}

/*
 * cnp_buf_resize()
 *
 * Resize the buffer <buf> to the new size <newsize>.  If the new size is
 * smaller than the length of the buffer's content, it is truncated to fit
 * the new buffer.
 *
 * Returns 0 on success, or -1 on failure.
 */
int
cnp_buf_resize(cnp_buf_t *buf, size_t newsize)
{
	void *tmp;

	if ((tmp = realloc(buf->cb_buf, newsize)) == NULL) {
		cnp_log_err(cnp_logchan,
		    "failed to reallocate buffer");
		return (-1);
	}

	buf->cb_buf = tmp;
	buf->cb_size = newsize;
	if (buf->cb_len > buf->cb_size)
		buf->cb_len = buf->cb_size;

	return (0);
}

/*
 * cnp_buf_free()
 *
 * Free the buffer <buf> and all associated data.
 */
void
cnp_buf_free(cnp_buf_t *buf)
{
	if (buf->cb_buf != NULL)
		cnp_free(buf->cb_buf);
	cnp_free(buf);
}

/*
 * cnp_buf_unwrap()
 *
 * Free the buffer <buf>'s structural information but do not free the contents
 * of the buffer.  Instead, they are returned and should be freed later using
 * free().
 */
uint8_t*
cnp_buf_unwrap(cnp_buf_t *buf)
{
	uint8_t *tmp;

	tmp = buf->cb_buf;
	cnp_free(buf);
	return (tmp);
}

/*
 * cnp_buf_empty()
 *
 * Empty the contents of the buffer <buf> and reset pointers.
 */
void
cnp_buf_empty(cnp_buf_t *buf)
{
	buf->cb_len = 0;
	buf->cb_pos = 0;
}

/*
 * cnp_buf_setc()
 *
 * Set the value of a single character <c> to the end of the buffer <buf>.
 *
 * Returns 0 if the character was successfully appended to the buffer, or -1
 * if there was not sufficient space.
 */
int
cnp_buf_setc(cnp_buf_t *buf, size_t off, int c)
{
	if (off >= buf->cb_len) {
		cnp_log(cnp_logchan, CNP_LOG_ERROR,
		    "cnp_buf_setc: offset too large");
		return (-1);
	}

	buf->cb_buf[buf->cb_pos + off] = c;

	return (0);
}

/*
 * cnp_buf_putc()
 *
 * Append a single character <c> to the end of the buffer <buf>.
 *
 * Returns 0 if the character was successfully appended to the buffer, or -1
 * if there was not sufficient space.
 */
int
cnp_buf_putc(cnp_buf_t *buf, int c)
{
	uint8_t val = (uint8_t)c;

	return cnp_buf_append(buf, &val, sizeof(val));
}

/*
 * cnp_buf_getc()
 *
 * Remove the first available character from the start of the buffer <buf>
 * and returns it on success, or -1 if no characters are available.
 */
int
cnp_buf_getc(cnp_buf_t *buf)
{
	int c = -1;

	if (buf->cb_len > 0) {
		c = buf->cb_buf[buf->cb_pos++];
		buf->cb_len--;
	}

	return (c);
}

/*
 * cnp_buf_ungetc()
 *
 * Put the character <c> (converted to a char) back at the start of the
 * buffer <buf>.
 *
 * Returns 0 on success, or -1 on failure.
 */
int
cnp_buf_ungetc(cnp_buf_t *buf, int c)
{
	if (buf->cb_pos == 0) {
		if (buf->cb_len == 0)
			buf->cb_pos = 1;
		else
			return (-1);
	}

	buf->cb_pos--;
	buf->cb_buf[buf->cb_pos] = (uint8_t)c;
	buf->cb_len++;

	return (0);
}

/*
 * cnp_buf_find()
 *
 * Find the first occurrence of the byte sequence <seq>, whose length is
 * specified in <len>, in the contents of the buffer <buf>, starting at
 * offset <off>.
 *
 * Returns the offset from the start of the buffer at which the first
 * occurrence of the sequence was found, or -1 if the sequence was not found
 * in the buffer.
 */
ssize_t
cnp_buf_find(cnp_buf_t *buf, size_t off, const uint8_t *seq, size_t len)
{
	unsigned int i;
	const uint8_t *bp, *endp;
	ssize_t ret = -1;

	if ((off >= buf->cb_len) || (len > (buf->cb_len - off)) || (len == 0))
		return (-1);

	endp = buf->cb_buf + buf->cb_pos + buf->cb_len;

	for (bp = buf->cb_buf + buf->cb_pos + off; bp < endp; bp++) {
		if (*bp != *seq)
			continue;

		for (i = 1; i < len; i++)
			if (bp[i] != seq[i])
				break;

		if (i == len) {
			ret = bp - buf->cb_buf;
			break;
		}
	}

	return (ret);
}

/*
 * cnp_buf_append()
 *
 * Append <len> bytes of data pointed to by <data> to the buffer <buf>.  If the
 * buffer is too small to accept all data, it will attempt to append as much
 * data as possible, or if the CNP_BUF_AUTOEXT flag is set for the buffer, it
 * will get resized to an appropriate size to accept all data.
 *
 * Returns the number of bytes successfully appended to the buffer.
 */
ssize_t
cnp_buf_append(cnp_buf_t *buf, const void *data, size_t len)
{
	size_t left, rlen;
	uint8_t *bp;

	rlen = len;
	left = buf->cb_size - (buf->cb_pos + buf->cb_len);

	if (left < len) {
		if ((buf->cb_flags & CNP_BUF_AUTOEXT) &&
		    (cnp_buf_resize(buf, buf->cb_size + len - left) == -1)) {
			return (-1);
		}
		else
			rlen = left;
	}

	bp = buf->cb_buf + buf->cb_pos + buf->cb_len;

	memcpy(bp, data, rlen);
	buf->cb_len += rlen;

	return (rlen);
}

/*
 * cnp_buf_fappend()
 *
 * Append a string of bytes produced from a printf()-style format string <fmt>
 * and the necessary optional arguments to the buffer <buf>.  If the
 * buffer is too small to accept all data, it will attempt to append as much
 * data as possible, or if the CNP_BUF_AUTOEXT flag is set for the buffer, it
 * will get resized to an appropriate size to accept all data.
 *
 * Returns the number of bytes successfully appended to the buffer.
 */
ssize_t
cnp_buf_fappend(cnp_buf_t *buf, const char *fmt, ...)
{
	ssize_t ret;
	char *str;
	va_list vap;

	va_start(vap, fmt);
	ret = cnp_vasprintf(&str, fmt, vap);
	va_end(vap);

	if (ret == -1)
		cnp_log_err(cnp_logchan,
		    "cnp_buf_fappend: failed to format data");

	ret = cnp_buf_append(buf, str, (size_t)ret);
	cnp_free(str);
	return (ret);
}

/*
 * cnp_buf_len()
 *
 * Returns the length of data currently stored in the buffer <buf>.
 */
size_t
cnp_buf_len(cnp_buf_t *buf)
{
	return (buf->cb_len);
}

/*
 * cnp_buf_writefd()
 *
 * Write the contents of the buffer <buf> to the file descriptor <fd>.
 *
 * Returns 0 on success, or -1 on failure.
 */
int
cnp_buf_writefd(cnp_buf_t *buf, int fd)
{
	uint8_t *bp;
	size_t len;
	ssize_t ret;

	len = buf->cb_len;
	bp = buf->cb_buf + buf->cb_pos;

	do {
		ret = write(fd, bp, len);
		if (ret == -1) {
			if (errno == EINTR || errno == EAGAIN)
				continue;

			cnp_log_errno(cnp_logchan,
			    "cnp_buf_writefd: write error");
			return (-1);
		}

		len -= (size_t)ret;
		bp += (size_t)ret;
	} while (len > 0);

	return (0);
}

/*
 * cnp_buf_write()
 *
 * Write the contents of the buffer <buf> to the file whose path is given in
 * <path>.  If the file does not exist, it is created with mode <mode>.
 */
int
cnp_buf_write(cnp_buf_t *buf, const char *path, mode_t mode)
{
	int fd;
 open:
	if ((fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, mode)) == -1) {
		if (errno == EACCES && unlink(path) != -1)
			goto open;
		else
			cnp_log_errno(cnp_logchan, "open: `%s'", path);
	}

	if (cnp_buf_writefd(buf, fd) == -1) {
		(void)unlink(path);
		cnp_log_err(cnp_logchan,
		    "cnp_buf_write: cnp_buf_writefd: `%s'", path);
	}

	if (fchmod(fd, mode) < 0)
		cnp_log_err(cnp_logchan,
		    "permissions not set on file %s", path);

	(void)close(fd);

	return (0);
}

/*
 * cnp_buf_copy()
 *
 * Copy the first <len> bytes of data in the buffer <buf> starting at offset
 * <off> in the destination buffer <dst>, which can accept up to <len> bytes.
 * Returns the number of bytes successfully copied, or -1 on failure.
 */
ssize_t
cnp_buf_copy(cnp_buf_t *buf, size_t off, void *dst, size_t len)
{
	size_t rc;

	if (off >= buf->cb_len) {
		cnp_log_err(cnp_logchan, "cnp_buf_copy failed");
		return (-1);
	}

	rc = MIN(len, (buf->cb_len - off));
	memcpy(dst, buf->cb_buf + buf->cb_pos + off, rc);

	return (ssize_t)rc;
}

/*
 * cnp_buf_peek()
 *
 * Peek at the contents of the buffer <buf> at offset <off>.
 */
const uint8_t*
cnp_buf_peek(cnp_buf_t *buf, size_t off)
{
	if (off >= buf->cb_len)
		return (NULL);

	return (buf->cb_buf + buf->cb_pos + off);
}

/*
 * cnp_buf_cmp()
 *
 * Compare the two buffers <b1> and <b2> for equality.
 *
 * Returns 0 if the content of both buffers is the same.
 */
int
cnp_buf_cmp(const cnp_buf_t *b1, const cnp_buf_t *b2)
{
	if (b1->cb_len != b2->cb_len)
		return (1);

	return (memcmp(b1->cb_buf + b1->cb_pos, b2->cb_buf + b2->cb_pos,
	    b1->cb_len));
}
